package com.stedu.service.impl;

import com.stedu.bean.Department;
import com.stedu.exception.SteduException;
import com.stedu.mapper.DepartmentMapper;
import com.stedu.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @CacheEvict(value = "department", key = "'departmentList'")
    @Override
    public boolean insert(Department d) throws SteduException {
        //判断被添加的部门名称是否已经存在
        if(departmentMapper.selectByDname(d.getDname()) != null) {
            //抛出自定义异常
            throw new SteduException("该部门已经存在，无法重复添加");
        }

        return departmentMapper.insert(d) == 1;
    }

    @Caching(
            evict = {
                    @CacheEvict(value = "department", key = "'departmentList'"),
                    @CacheEvict(value = "department", key = "#did")
            }
    )
    @Override
    public boolean delete(Integer did) throws SteduException {
        if (departmentMapper.selectByDid(did) == null) {
            throw new SteduException("该部门不存在，无法删除");
        }

        // 判断该部门下是否有员工
        int employeeCount = departmentMapper.hasEmployeesInDepartment(did);
        if (employeeCount > 0) {
            throw new SteduException("该部门下存在员工，无法删除");
        }

        return departmentMapper.delete(did) == 1;
    }

    @Caching(
            evict = {
                    @CacheEvict(value = "department", key = "'departmentList'"),
                    @CacheEvict(value = "department", key = "#d.did")
            }
    )

    @Override
    public boolean update(Department d) throws SteduException {
        if(departmentMapper.selectByDid(d.getDid()) == null) {
            throw new SteduException("该部门不存在，无法修改");
        }
        /*
         *  修改之后的名字不能和其他部门的名字重复
         *   1. 根据修改之后的名字（d.getDname()）查询
         *   2. 能查到/查到的是其他部门
         * */
        //根据修改之后的名字（d.getDname()）查询
        Department d1 = departmentMapper.selectByDname(d.getDname());
        if(d1 != null && d1.getDid() != d.getDid()) {
            throw new SteduException("修改之后的名字和其他部门的名字重复，不允许修改");
        }

        return departmentMapper.update(d) == 1;
    }
    @Cacheable(value = "department",key = "#did",unless = "#result == null")
    @Override
    public Department selectByDid(Integer did) {
        return departmentMapper.selectByDid(did);
    }

//    @Cacheable(value = "department", key = "'departmentList'",unless = "#result == null || #result.size() == 0")
    @Override
    public List<Department> selectAll() {
        return departmentMapper.selectAll();
    }
}
